<template>

    <div class="formula-container">
        <div class="formula-toolbar">
            <a-button type="primary" @click="handOk">{{i18n('formula.save', '保存')}}</a-button>
            <a-button @click="cancel">{{i18n('formula.cancel', '取消')}}</a-button>
        </div>
        <a-form-model ref="ruleForm" layout="vertical" :model="source" :rules="rules" style="padding: 12px 12px 12px 22px;overflow-y: scroll;">
            <a-row :gutter="24">
                <a-col :span="12">
                    <a-form-model-item :label="i18n('formula.notes', '备注')" prop="notes">
                        <a-input  v-model="source.notes" :placeholder="i18n('formula.sayFormula', '说明公式的作用')"></a-input>
                    </a-form-model-item>
                </a-col>
                <a-col :span="12">
                    <a-form-model-item :label="i18n('formula.sourceTable', '源表')">
                        {{source.comment}}
                    </a-form-model-item>
                </a-col>
            </a-row>
            <a-row :gutter="24">
                <a-col :span="12">
                    <a-form-model-item :label="i18n('formula.dataSource', '数据源')">
                        <rx-input-button v-model="source.dsLabelObj" :placeholder="i18n('formula.defSource', '不填默认当前数据源')"
                                         @click="handlerDataSource" @change="dsLabelChange"></rx-input-button>
                    </a-form-model-item>
                </a-col>
                <a-col :span="12">
                    <a-form-model-item :label="i18n('formula.form', '目标表')"  prop="tableName">
                        <rx-input-button v-model="source.tableNameObj" @click="onAddTableMap" @change="tableNameChange"></rx-input-button>
                    </a-form-model-item>
                </a-col>
            </a-row>
            <a-form-model-item :label="i18n('formula.tips', '源表数据变化时触发一下操作')">

                <a-radio-group v-model="source.operator" class="rx-radio-group">
                    <a-radio-button value="new">
                        <div class="radio-row">
                            <div class="radio-row-title">{{i18n('formula.addData', '新建数据')}}</div>
                            <div class="radio-row-text">{{i18n('formula.addDataTips', '向目标表新建数据')}}</div>
                        </div>
                    </a-radio-button>
                    <a-radio-button value="upd">
                        <div class="radio-row">
                            <div class="radio-row-title">{{i18n('formula.renew', '更新数据')}}</div>
                            <div class="radio-row-text">{{i18n('formula.renewTips', '根据条件更新目标表数据')}}</div>
                        </div>
                    </a-radio-button>
                    <a-radio-button value="del">
                        <div class="radio-row">
                            <div class="radio-row-title">{{i18n('formula.delData', '删除数据')}}</div>
                            <div class="radio-row-text">{{i18n('formula.delDataTips', '删除目标表的数据')}}</div>
                        </div>
                    </a-radio-button>

                </a-radio-group>

            </a-form-model-item>
            <template v-if="source.operator!=='new'">
                <a-form-model-item :label="i18n('form.filterStatement','过滤条件')"  prop="filterSql">
                    <a-input-group compact>
                        <a-input v-model="source.filterSql"  style="width: calc(100% - 80px)"/>
                        <a-button @click="filterSqlConf">
                            {{ $comi18('rxDialog.designer', '设计') }}
                        </a-button>
                    </a-input-group>
                </a-form-model-item>
            </template>

            <template v-if="source.tableName">
                <a-form-model-item :label="i18n('formula.runCondition', '执行条件')">
                    <FormTableFormulaCondition ref="condition"   :source="source"></FormTableFormulaCondition>
                </a-form-model-item>
                <FormulaFieldMapping v-if="source.operator !== 'del'" :value="source" ref="mapping"></FormulaFieldMapping>
            </template>
        </a-form-model>
    </div>

</template>

<script>
import formBoControls from "@/api/form/bo/formBoControls";
import {Dialog, Util,JsConstant} from "@lowcode/jpaas-common-lib"
import FormTableFormulaFilterSql from "@/views/modules/form/core/FormTableFormulaFilterSql";
import FormulaFieldMapping from "./FormulaFieldMapping.vue";
import FormTableFormulaCondition from './FormTableFormulaCondition.vue'
import {cloneDeep} from 'lodash-es';
import AppName from "@/assets/js/AppName.js";

/**
 * @Author : yangsanjin
 * @Date: 2024-09-13 14:13
 */
export default {
    name: "FormTableFormula",
    mixins: [formBoControls,AppName],
    props:{
        /**
         * {
         *     boDefId:'',
         *     boName:'',
         *     isMain:'',
         *     type
         * }
         */
        config:{},
        layerid:{},
        destroy:{}
    },
    components:{
        FormulaFieldMapping,
        FormTableFormulaCondition
    },
    data(){
        return {
            rules:{
                notes:[ { required: true, message: this.i18n('formula.required', '必填'), trigger: 'blur' }],
                tableName:[ { required: true, message: this.i18n('formula.required', '必填'), trigger: 'blur' }],
                filterSql:[ { required: true, message: this.i18n('formula.required', '必填'), trigger: 'blur' }]
            },
            source:{
                //业务模型ID
                boDefId:'',
                //实体名称
                boName:'',
                //备注
                notes:'',
                //操作类型
                operator:'new',
                //目标表
                tableName:'',
                //过滤语句
                filterSql:'',
                //执行条件
                condition:'',
                //easy,script
                conditionType:'',
                //简易执行条件
                easyCondition:{
                    condition: "AND",
                    rule:[]
                },
                //字段映射
                gridData:[],
                //是否为主表
                isMain:'yes',
                //数据源名称
                dsLabel:'',
                //数据源key
                dsName:'',
                //type main,onetoone,onetomany
                type:'',
                //来源表
                comment:""
            }
        }
    },
    created(){
        if(this.config){
            Object.assign(this.source,this.config) ;
            this.source.conditionType = this.source.condition?'script' : 'easy' ;
        }
    },
    methods:{
        i18n(name, text, key) {
            return this.$ti18(name, text, "formTableFormula", key);
        },
        dsLabelChange(value){
            if(!value) {
              this.source.dsLabel = "";
              this.source.dsName = "";
            }
        },
        tableNameChange(value){
            if(!value){
              this.source.tableName = "";
            }
        },
        handlerDataSource(vm) {
            Dialog.openDataSourceDialog({
                curVm: this,
                widthHeight: ['800px', '600px'],
                data:{appName: this.serviceName}
            },  (self, data)=> {
                if(data){
                    this.source.dsLabel = data.name
                    this.source.dsName = data.alias
                }
                else {
                    this.source.dsLabel = "";
                    this.source.dsName = "";
                }
                vm.setVal(this.source.dsName,this.source.dsLabel);
            })
        },
        onAddTableMap(vm) {
            let {dsName} = this.source;
            Dialog.openTableQueryDialog({
                curVm: this, widthHeight: ['1200px', '600px'], data: {ds: dsName}
            },  (self, data)=> {
                if(data){
                   this.source.tableName = data.tableName ;
                   vm.setVal(this.source.tableName);
                }
            })
        },
        filterSqlConf() {
            let self = this;
            let {filterSql:value,boDefId,boName:entName,tableName,dsName} = this.source ;
            let baseConf = {
                "curVm": self,
                component: FormTableFormulaFilterSql,
                title: this.i18n('list.title2', '设置过滤条件'),
                widthHeight: ['1000px', '500px'],
                data: {
                    value,
                    boDefId,
                    entName,
                    tableName,
                    dsName
                }
            };
            Util.open(baseConf, function (action, data) {
                if (action != 'ok') return;
                self.source.filterSql = data;
            });
        },
        handOk(){
            this.$refs.ruleForm.validate(valid => {
                if (valid) {
                    let { source } = this ;
                    let gridData = [],rows=[];
                    if(this.$refs.mapping){
                        gridData = this.$refs.mapping.getData();

                        if(gridData.length>0) {
                            for(let i=0;i<gridData.length;i++){
                                let row= gridData[i];
                                let newRow={
                                    isPk:row.isPk,
                                    fieldName:row.fieldName,
                                    columnType:row.columnType,
                                    mapType:row.mapType,
                                    mapValue:row.mapValue,
                                    mapTypeName:row.mapTypeName,
                                    comment:row.comment,
                                    isNull:row.isNull,
                                    charLen:row.charLen,
                                    decimalLen:row.decimalLen,
                                    intLen:row.intLen
                                }
                                rows.push(newRow);
                            }
                        }
                    }
                    let easyCondition = this.$refs['condition']?.getEasyCondition()
                    let rtn= cloneDeep({
                        ...source,
                        gridData:rows,
                        easyCondition:easyCondition ?? {}
                    })
                    if(['new','upd'].includes(this.source.operator) && rows.length === 0){
                        this.$message.warning(this.i18n('formula.noCheckTips','校验不通过，字段映射必须要有字段！'))
                    }else {
                        this.$emit('confirm',rtn)
                    }
                } else {
                    this.$message.warning(this.i18n('formula.noCheckTips2','校验不通过，请检查必填项！'))
                    return false;
                }
            });

        },
        cancel(){
            this.$emit('cancel')
        }
    }
}
</script>

<style scoped>
.formula-container{
    width: 100%;
    height: 100%;
    display:grid;
    grid-template-rows:  auto 1fr;
    overflow: hidden;
}
.rx-radio-group >>> .ant-radio-button-wrapper{
    height: auto;
    line-height: normal;
}
.formula-container >>> .ant-form-item-label{
    font-weight: bold;
}
.formula-toolbar{
    text-align: right;
    padding: 10px;
    border-bottom: 1px solid #e9e9e9;
}
.formula-toolbar button:not(:first-child){
    margin-left: 10px;
}
.radio-row .radio-row-title{
    padding-bottom: 6px;
}
.radio-row{
    line-height: 20px;
    padding: 10px 0;
}
.rx-radio-group >>> .ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled){
    background-color: #1890ff;
    color: #fff;
}
</style>